package com.pet.platform.util;

import com.pet.platform.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

@Component
public class FileUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    
    @Value("${upload.path}")
    private String uploadPath;
    
    @Value("${upload.allowed-types}")
    private String allowedTypes;
    
    @Value("${upload.max-size}")
    private Long maxSize;
    
    public String uploadFile(MultipartFile file, String directory) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }
        
        // 检查文件大小
        if (file.getSize() > maxSize) {
            throw new BusinessException("文件大小不能超过" + maxSize / 1024 / 1024 + "MB");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (!Arrays.asList(allowedTypes.split(",")).contains(contentType)) {
            throw new BusinessException("不支持的文件类型");
        }
        
        try {
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;
            
            // 使用项目根目录来构建绝对路径
            String projectRoot = System.getProperty("user.dir");
            Path uploadsDir = Paths.get(projectRoot, "target", "classes", "static", "images", directory);
            logger.info("尝试上传文件到目录: {}", uploadsDir);
            
            // 确保目录存在
            if (!Files.exists(uploadsDir)) {
                try {
                    Files.createDirectories(uploadsDir);
                    logger.info("已创建目录: {}", uploadsDir);
                } catch (IOException e) {
                    logger.error("无法创建目录: {}", uploadsDir, e);
                    throw new BusinessException("无法创建上传目录: " + e.getMessage());
                }
            }
            
            // 构建文件完整路径
            Path filePath = uploadsDir.resolve(filename);
            logger.info("文件将被保存到: {}", filePath);
            
            // 使用Files API保存文件
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, filePath, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                logger.info("文件上传成功: {}", filePath);
            } catch (IOException e) {
                logger.error("文件复制失败", e);
                throw new BusinessException("文件上传失败: " + e.getMessage());
            }
            
            // 返回文件访问路径
            return "/images/" + directory + "/" + filename;
        } catch (Exception e) {
            logger.error("文件上传过程中发生异常", e);
            throw new BusinessException("文件上传失败: " + e.getMessage());
        }
    }
    
    public void deleteFile(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return;
        }
        
        try {
            // 构建绝对路径
            String projectRoot = System.getProperty("user.dir");
            Path file = Paths.get(projectRoot, "src", "main", "resources", "static", filePath);
            
            // 删除文件
            if (Files.exists(file) && Files.isRegularFile(file)) {
                Files.delete(file);
                logger.info("文件已删除: {}", file);
            } else {
                logger.warn("尝试删除不存在的文件: {}", file);
            }
        } catch (IOException e) {
            logger.error("删除文件失败", e);
        }
    }
} 